package com.aiwiown.snackmq.common.serialization;

import com.aiwiown.snackmq.common.serialization.constants.SerializerAlgorithm;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 序列化器工厂，用于获取和管理序列化器实例。
 */
public final class SerializerFactory {

    private static final Map<Byte, Serializer> SERIALIZER_MAP = new ConcurrentHashMap<>();

    static {
        JsonSerializer jsonSerializer = new JsonSerializer();
        ProtobufSerializer protobufSerializer = new ProtobufSerializer();

        SERIALIZER_MAP.put(jsonSerializer.getAlgorithmId(), jsonSerializer);
        SERIALIZER_MAP.put(protobufSerializer.getAlgorithmId(), protobufSerializer);
    }

    private SerializerFactory() {}

    /**
     * 根据算法ID获取序列化器实例。
     */
    public static Serializer getSerializer(byte algorithmId) {
        Serializer serializer = SERIALIZER_MAP.get(algorithmId);
        if (serializer == null) {
            throw new IllegalArgumentException("未知的序列化算法ID: " + algorithmId);
        }
        return serializer;
    }

    /**
     * 获取默认的JSON序列化器实例。
     */
    public static JsonSerializer getJsonSerializer() {
        return (JsonSerializer) getSerializer(SerializerAlgorithm.JSON);
    }
}